package com.example.demorabbitmqlisten.rabbitmq;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Jackson工具类
 *
 * @author rockzhan 2021-04-09 8:53
 * @version 1.0
 */
public class JacksonUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static{
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    }

    /**
     * 对json字符串进行自然排序
     *
     * @param json 待排序json字符串
     * @return 自然排序后json字符串
     * @author rockzhan 2021-04-09 8:57
     */
    public static String sortJson(String json){
        try{
            JsonNode jsonNode = MAPPER.readTree(json);
            Object jsonObj = MAPPER.treeToValue(jsonNode, Object.class);
            return MAPPER.writeValueAsString(jsonObj);
        }catch(JsonProcessingException e){
            return json;
        }
    }
}
